package com.harvest.scientific.ladder.net

import android.util.Log
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okio.Buffer
import java.io.IOException
import java.nio.charset.Charset

class LogCeptor : Interceptor {

    private val UTF8 = Charset.forName("UTF-8")
    private val TAG = LogCeptor::class.java.simpleName

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request: Request = chain.request()
        val response: Response
        try {
            response = chain.proceed(request)
            var buffer: Buffer? = null
            try {
                val source = response.body?.source()
                source?.request(Long.MAX_VALUE)
                buffer = source?.buffer?.clone()
            } catch (e: Exception) {
                Log.d(TAG, "e:${e.stackTraceToString()}")
            }
            try {
                val localLog = StringBuilder()
                localLog.append("[")
                    .append("\r\n")
                    .append("method:${request.method}")
                    .append("\r\n")
                    .append("url:${request.url}")
                    .append("\r\n")
                    .append("${buffer?.clone()?.readString(UTF8)}")
                    .append("\r\n")
                    .append("]")
                Log.d(TAG, "responseBody: $localLog")
            } catch (e: Exception) {
                Log.d(TAG, "responseBody e: ${e.stackTraceToString()}")
            }
            return response
        } catch (e: Exception) {
            Log.d(TAG, "chain.proceed e:" + Log.getStackTraceString(e))
            throw e
        }
    }
}
